package com.example.demo.service.impl;

import com.example.demo.entity.MonitorcodeInfo;
import com.example.demo.entity.MonitorobjInfo;
import com.example.demo.service.TestAccessService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 验证web服务是否可以联通的实现类
 * Created by tanjun on 2021-12-30.
 */
@Component
public class TestWebServiceAccessService extends BaseAccessService implements TestAccessService {

    public static void main(String[] args) {
        TestWebServiceAccessService testservice=new TestWebServiceAccessService();
        testservice.testAccess("");
    }

    public void testAccess(String monitorObjId){
        //从数据库获取服务url信息，请求方式，请求参数
        MonitorobjInfo monitorobjInfo=monitorobjInfoMapper.selectByPrimaryKey(monitorObjId);
        if(monitorobjInfo.getMonitorobjCodeId()==null){
            return;
        }
        MonitorcodeInfo monitorcodeInfo=monitorcodeInfoMapper.selectByPrimaryKey(monitorobjInfo.getMonitorobjCodeId());
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Get请求
        HttpGet httpGet = new HttpGet(monitorcodeInfo.getUrl());
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            //4.判断状态码
            if(response.getStatusLine().getStatusCode()==200){
                //可以进一步验证返回实体中的内容，但是我们简单点，只要返回200就算是可访问的。
                //使用工具类EntityUtils，从响应中取出实体表示的内容并转换成字符串
                /*HttpEntity entity = response.getEntity();
                String string = EntityUtils.toString(entity, "utf-8");*/
                //System.out.println("true");
                accessTestResultHandler.handlerAccessTestSuccess(monitorObjId,monitorcodeInfo.getMonitorcodeId());
            }else{
                accessTestResultHandler.handlerAccessTestfailure(monitorObjId,monitorcodeInfo.getMonitorcodeId());
            }
        }  catch (IOException e) {
            e.printStackTrace();
            accessTestResultHandler.handlerAccessTestfailure(monitorObjId,monitorcodeInfo.getMonitorcodeId());
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
